<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :text="`当前共有${total}条记录`">
        <el-button
          :disabled="!checkBtnPermission('employee_import')"
          @click="$router.push('/import?type=user')"
          size="small"
          type="danger"
        >
          Excel导入
        </el-button>
        <el-button
          :disabled="!checkBtnPermission('employee_export')"
          @click="exportFn1"
          size="small"
          type="warning"
        >
          普通表头Excel导出
        </el-button>
        <el-button
          :disabled="!checkBtnPermission('employee_export')"
          @click="exportFn2"
          size="small"
          type="success"
        >
          复杂表头Excel导出
        </el-button>
        <el-button
          @click="$refs.addEmp.dialogShow = true"
          size="small"
          type="primary"
        >
          新增员工
        </el-button>
      </PageTools>

      <el-card>
        <el-table :data="tableData" border @selection-change="selectionChange">
          <el-table-column type="selection" />
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" sortable="">
            <template v-slot="scope">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="scope.row.staffPhoto"
                style="height: 60px"
                alt=""
                @click="showCode(scope.row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column
            label="聘用形式"
            :formatter="formatterFn"
            prop="formOfEmployment"
          ></el-table-column>

          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="scope">
              <el-button
                @click="$router.push('/employees/detail/' + scope.row.id)"
                type="text"
                size="small"
              >
                查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                @click="openRole(scope.row.id)"
                type="text"
                size="small"
              >
                角色
              </el-button>
              <el-button @click="delRow(scope.row.id)" type="text" size="small">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          @size-change="sizeChange"
          @current-change="pageChange"
          :current-page.sync="queryData.page"
          :page-sizes="[10, 40, 80, 100]"
          :page-size="queryData.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-card>
      <!-- 新增弹框 -->
      <AddEmployees ref="addEmp" @updataList="iniData"></AddEmployees>
      <!-- 图片二维码弹框 -->
      <el-dialog title="预览二维码" :visible.sync="dialogCodeShow">
        <!-- 存放一个二维码的canvas画布标签 -->
        <canvas id="canvas" style="display: block; margin: 0 auto"></canvas>
      </el-dialog>
      <!-- 角色设置弹框 -->
      <SetRole ref="setRole"></SetRole>
    </div>
  </div>
</template>

<script>
import { getEmployeesListApi, delEmployeesApi } from '@/api/employees'
import EmployessEnum from '@/api/constant/employees'
import AddEmployees from './components/addEmployees.vue'
import { formatDate } from '@/filters'
import SetRole from './components/setRole.vue'
import QRCode from 'qrcode'
// import PageTools from '@/components/PageTools'
export default {
  // components: {
  //   PageTools
  // }
  name: 'Employees',
  components: {
    AddEmployees,
    SetRole
  },
  data() {
    return {
      // 表格渲染列表数据
      tableData: [],
      queryData: {
        page: 1,
        size: 10
      },
      // 分页下方显示的总数
      total: 0,
      // 存储选中数据
      checkTableData: [],
      dialogCodeShow: false
    }
  },
  created() {
    // 生命周期调用
    this.iniData()
  },
  methods: {
    // 获取员工数据列表
    async iniData() {
      const { rows, total } = await getEmployeesListApi(this.queryData)
      console.log(rows, total)
      this.tableData = rows
      this.total = total
    },
    // 每页最大数量切换时触发
    sizeChange(val) {
      this.queryData.size = val
      this.iniData()
    },
    // 页码切换时触发
    pageChange(val) {
      this.queryData.page = val
      this.iniData()
    },
    // 对聘用的列 格式化操作 formatterFn是什么prop="xxx"拿到的值就是什么
    // 需要有prop="xxx" 才能拿到对应表格数据
    formatterFn(row, column, cellValue, index) {
      // row 行数据，column 列信息，cellValue 单元格值，index 行索引
      const res = EmployessEnum.hireType.find(
        (item) => item.id === cellValue * 1
      )
      return res ? res.value : '未知'
    },
    // 删除事件
    async delRow(id) {
      try {
        await this.$confirm('确认删除吗？')
      } catch {
        return
      }
      // 发请求
      await delEmployeesApi(id)
      this.$message.success('删除成功')
      // 边缘问题
      if (this.queryData.page > 1 && this.tableData.length === 1) {
        this.queryData.page--
      }
      //
      this.iniData()
    },
    // 普通表头Excel导出
    exportFn1() {
      // 1.按需加载导出的Excel模块
      import('@/vendor/Export2Excel').then(async (excel) => {
        // console.log(excel)=> excel就是加载好的模块
        // 2.获取需要导出的数据
        const { rows } = await getEmployeesListApi({
          page: 1,
          size: 99999999
        })
        // 3.调用整理数据函数
        const res = this.generateData(rows)
        // console.log(excel)
        // 4.excel导出模块
        excel.export_json_to_excel({
          header: res.headerKey, //, //表头 必填
          data: res.bodyData, // 具体数据 必填
          filename: '员工数据', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 整理数据函数
    generateData(data) {
      // 数据模板
      const headers = {
        手机号: 'mobile',
        姓名: 'username',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const headerKey = Object.keys(headers)
      // console.log(headerKey)
      const result = []
      data.forEach((item) => {
        const row = []
        Object.keys(headers).forEach((val) => {
          if (headers[val] === 'formOfEmployment') {
            //
            const info = EmployessEnum.hireType.find(
              (obj) => obj.id === item[headers[val]] * 1
            )
            row.push(info ? info.value : '未知')
          } else if (['timeOfEntry', 'correctionTime'].includes(headers[val])) {
            row.push(formatDate(item[headers[val]]))
          } else {
            row.push(item[headers[val]])
          }
        })
        result.push(row)
      })
      return { headerKey, bodyData: result }
    },
    // 表格勾选时触发
    selectionChange(val) {
      // val是勾选的数据
      this.checkTableData = val
    },

    // 复杂表头导出
    async exportFn2() {
      // 加载 Excel 模块
      const excel = await import('@/vendor/Export2Excel')
      // 获取数据，整理数据
      if (!this.checkTableData.length) {
        return this.$message.warning('请勾选数据')
      }

      const res = this.generateData(this.checkTableData)
      // 3.调用导出 Excel 文件
      // console.log(res)
      excel.export_json_to_excel({
        header: res.headerKey, //, //表头 必填
        multiHeader: [['基本信息', '', '', '', '', '', '部门']], // 复杂表头部分
        merges: ['A1:F1', 'G1:G2'], // 合并规则
        data: res.bodyData, // 具体数据 必填
        filename: '员工数据', // 非必填
        autoWidth: true, // 非必填
        bookType: 'xlsx' // 非必填
      })
    },
    showCode(url) {
      if (!url) return
      this.dialogCodeShow = true
      this.$nextTick(() => {
        const canvas = document.querySelector('#canvas')
        // QRCode.toCanvas(画布标签dom节点,转成二维码的内容,回调函数)
        QRCode.toCanvas(canvas, url, function (err) {
          if (err) console.error(err)
          console.log('success!')
        })
      })
    },
    // 打开角色设置
    async openRole(id) {
      // 调用子级获取所有角色函数
      await this.$refs.setRole.getAllRoleList()
      // 调用子级获取当前员工信息函数
      await this.$refs.setRole.getCurrentRole(id)
      // 打开弹框
      this.$refs.setRole.dialogShow = true
    }
  }
}
</script>

<style></style>
